<?php

namespace common\app;

use common\models\AccountModel;
use yii;

class Log
{
    //记录访问日志
    public function access($isend = false, $resData = [])
    {
        $pageNumber = PAGE_NUMBER;
        $useTime = (float)((($this->etime()) - STIME) / 1000);
        $url = $this->url();
        if (empty($url))
            return;


        if ($isend) {
            \Cm::$db->update("scrm_weixin_log_access",
                ['usetime' => $useTime, 'res' => json_encode($resData)],
                "page_number='{$pageNumber}'");
        } else {


            $data['sys_name'] = APPNAME;
            $data['page_number'] = $pageNumber;
//            $data['store_id'] = $account->storeID;
//            $data['account_id'] = $account->accountID;
            $data['url'] = $url;
            $data['route'] = Yii::$app->controller->route;
            $data['is_ajax'] = Yii::$app->request->isAjax;
            $data['method'] = Yii::$app->request->method;
            $data['req_input'] = file_get_contents("php://input");
            $data['req_get'] = $this->req_get();
            $data['req_post'] = json_encode($_POST);
            $data['ip'] = $this->ip();
            $data['user_agent'] = isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'';
            $data['usetime'] = $useTime;
            $data['addtime'] = time();

            \Cm::$db->insert('scrm_weixin_log_access', $data);
        }
    }

    private function etime()
    {
        list($t1, $t2) = explode(' ', microtime());
        $etime = (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
        return $etime;
    }

    private function url()
    {
        $url = 'http://' . $_SERVER['SERVER_NAME'] . ($_SERVER["SERVER_PORT"] == 80 ? '' : ':' . $_SERVER["SERVER_PORT"]) . $_SERVER["REQUEST_URI"];
        $urlArr = explode('?', $url);
        $url = $urlArr[0];
        if (strtolower($url) == strtolower(BASE_URL . '/favicon.ico'))
            $url = "";

        $route = Yii::$app->controller->route;
        if(strtolower($route)=='admin/main/404')
            $url = "";
        return $url;
    }

    public function ip()
    {
        $ip = ""; //getenv("REMOTE_ADDR");

        if (getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
        else $ip = "";

        $ips = explode(',', $ip);
        if (count($ips) > 0)
            $ip = $ips[0];

        return $ip;
    }

    private function req_get()
    {
        $route = Yii::$app->controller->route;
        $get = [];
        foreach ($_GET as $k => $p) {
            if (strtolower($k) != strtolower(yii\helpers\Url::to(["/{$route}"])))
                $get["{$k}"] = $p;
        }
        return json_encode($get);
    }

}

